package com.battle.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.entity.*;
import com.battle.pojo.enums.PersonMpWarCaseTypeEnum;
import com.battle.pojo.param.teamWarCase.*;
import com.battle.pojo.vo.carWarCase.GetCarWarCaseListVo;
import com.battle.pojo.vo.personMpWarCase.GetPersonMpWarCaseDownListVo;
import com.battle.pojo.vo.teamWarCase.*;
import com.battle.pojo.dto.teamWarCase.*;
import com.battle.service.repository.in.OrganizationRepository;
import com.battle.service.repository.in.PersonMpWarCaseRepository;
import com.battle.service.repository.in.PersonWarCaseRepository;
import com.battle.service.repository.in.TeamWarCaseRepository;
import com.battle.service.service.in.TeamWarCaseService;
import com.battle.service.utils.ExcelUtils;
import com.battle.service.utils.StringPassUtil;
import jakarta.servlet.http.HttpServletResponse;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：队伍战力表服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class TeamWarCaseServiceImpl implements TeamWarCaseService {

    private final TeamWarCaseRepository teamWarCaseRepository;
    private final PersonMpWarCaseRepository personMpWarCaseRepository;
    private final PersonWarCaseRepository personWarCaseRepository;
    private final OrganizationRepository organizationRepository;

    public TeamWarCaseServiceImpl(TeamWarCaseRepository teamWarCaseRepository, PersonMpWarCaseRepository personMpWarCaseRepository, PersonWarCaseRepository personWarCaseRepository, OrganizationRepository organizationRepository) {
        this.teamWarCaseRepository = teamWarCaseRepository;
        this.personMpWarCaseRepository = personMpWarCaseRepository;
        this.personWarCaseRepository = personWarCaseRepository;
        this.organizationRepository = organizationRepository;
    }


    /**
     * 创建队伍战力表
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTeamWarCase(CreateTeamWarCaseParam param) {
        TeamWarCase teamWarCase = new TeamWarCase();
        BeanUtils.copyProperties(param, teamWarCase);
        Long id = IdGenerator.SNOW.generate();
        teamWarCase.setId(id);
        // TODO 加一下创建人名称


        //随机生成60-100之间的数字
        teamWarCase.setCombatPower((int) (Math.random() * 40 + 60));

        //批量添加人员战力mp表
        personMpWarCaseRepository.bathAddPersonMpWarCase(PersonMpWarCaseTypeEnum.team, id, param.getPersonIds());
        teamWarCaseRepository.create(teamWarCase);
    }

    /**
     * 修改队伍战力表
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editTeamWarCase(EditTeamWarCaseParam param) {
        Long id = param.getId();
        TeamWarCase teamWarCase = teamWarCaseRepository.getByIdCheck(id);
        BeanUtils.copyProperties(param, teamWarCase);

        //批量移除人员mp表然后添加人员战力mp表
        personMpWarCaseRepository.removeByFidAndType(id, PersonMpWarCaseTypeEnum.team);
        personMpWarCaseRepository.bathAddPersonMpWarCase(PersonMpWarCaseTypeEnum.team, id, param.getPersonIds());

        teamWarCaseRepository.edit(teamWarCase);
    }

    /**
     * 移除队伍战力表
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeTeamWarCase(Long id) {
        teamWarCaseRepository.removeById(id);
        personMpWarCaseRepository.removeByFidAndType(id, PersonMpWarCaseTypeEnum.team);
    }



    /**
     * 获取队伍战力表详情
     *
     * @param id
     * @return
     */
    @Override
    public GetTeamWarCaseVo getTeamWarCase(Long id) {
        TeamWarCase teamWarCase = teamWarCaseRepository.getByIdCheck(id);
        GetTeamWarCaseVo vo = new GetTeamWarCaseVo();
        BeanUtils.copyProperties(teamWarCase, vo);


        List<PersonMpWarCase> byFidAndType = personMpWarCaseRepository.getByFidAndType(id, PersonMpWarCaseTypeEnum.team);
        if (CollectionUtil.isNotEmpty(byFidAndType)){
            List<Long> personIds = new ArrayList<>();
            for (PersonMpWarCase personMpWarCase : byFidAndType) {
                personIds.add(personMpWarCase.getPersonId());
            }
            vo.setPersonIds(personIds);
            //根据personIds批量查询
            List<PersonWarCase> personWarCases = personWarCaseRepository.listByIds(personIds);
            if (CollectionUtil.isNotEmpty(personWarCases)){
                //stream流提取personWarCases的name，用逗号分隔
                String personNames = personWarCases.stream()
                        .map(PersonWarCase::getName)
                        .collect(Collectors.joining(","));
                vo.setPersonNames(personNames);
            }
        }
        return vo;
    }

    /**
     * 获取队伍战力表 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetTeamWarCaseListVo> getTeamWarCaseList(GetTeamWarCaseListParam param) {

        SelectTeamWarCaseDto dto = new SelectTeamWarCaseDto();
        BeanUtils.copyProperties(param, dto);
        if (param.getOrderBy()!=null){
            dto.setOrderBy(StringPassUtil.convertToSnakeCase(param.getOrderBy()));
        }
        if (param.getOrganizationId()!=null){
            List<Long> ids = organizationRepository.getOrganizationIdList(param.getOrganizationId());
            dto.setOrganizationIds(ids);
        }
        Page<TeamWarCase> page = teamWarCaseRepository.selectTeamWarCase(dto);
        List<TeamWarCase> teamWarCaseList = page.getRecords();
        List<GetTeamWarCaseListVo> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(teamWarCaseList)){
            List<Long> ids = teamWarCaseList.stream().map(TeamWarCase::getId).toList();
            Map<Long, List<GetPersonMpWarCaseDownListVo>> listMap = personMpWarCaseRepository.getDtoByFids(ids);

            for (TeamWarCase teamWarCase : teamWarCaseList) {
                GetTeamWarCaseListVo vo = new GetTeamWarCaseListVo();
                BeanUtils.copyProperties(teamWarCase, vo);
                Long id = vo.getId();
                List<GetPersonMpWarCaseDownListVo> roleDtoList = listMap.get(id);
                if (roleDtoList != null) {
                    String personNames = roleDtoList.stream()
                            .map(GetPersonMpWarCaseDownListVo::getPersonName)
                            .collect(Collectors.joining(","));
                    vo.setPersonNames(personNames);
                }

                Organization byId = organizationRepository.getById(vo.getOrganizationId());
                if (byId != null) {
                    vo.setOrganizationName(byId.getName());
                }
                list.add(vo);
            }
        }
        return new PageResult<>(list, page);

    }

    @Override
    public void export(GetTeamWarCaseListParam param, HttpServletResponse response) throws IOException {
        param.setSize(Long.MAX_VALUE);
        PageResult<GetTeamWarCaseListVo> pageResult = getTeamWarCaseList(param);
        List<GetTeamWarCaseListVo> list = pageResult.getRecords();
        ExcelUtils.exportExcel(list, "队伍战力", "队伍战力", GetTeamWarCaseListVo.class, "队伍战力",response);

    }

    /**
     * 获取队伍战力表下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetTeamWarCaseDownListVo> getTeamWarCaseDownList(GetTeamWarCaseDownListParam param) {
        TeamWarCase po = new TeamWarCase();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
        }
        List<TeamWarCase> teamWarCaseList = teamWarCaseRepository.getListByEntity(po);

        List<GetTeamWarCaseDownListVo> list = new ArrayList<>();
        for (TeamWarCase teamWarCase : teamWarCaseList) {
            GetTeamWarCaseDownListVo vo = new GetTeamWarCaseDownListVo();
            BeanUtils.copyProperties(teamWarCase, vo);
            list.add(vo);
        }
        return list;
    }


}



